﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Reflection;
using Comm.PublicClass;
using System.Runtime.Serialization;
using Wasion.HHU.Data.Repositories;
using Wasion.HHU.Data.Models;

namespace WsProtocol.IEC62056MDL
{
    [DataContract]
    public class ProCaptureObj
    {
        private static ProtocolDbRepository protocolDbRepository = new ProtocolDbRepository();
        private static string ptltable = "T_CaptureObjs";
        private static DataTable dtAll = null;  //所有数据
        private static List<ProCaptureObj> EleItemlst = new List<ProCaptureObj>();    

        public string ObAttrID { get; set; }
        public string RelateAttrID { get; set; }
        public int Seq { get; set; }
        public int DataIndex { get; set; }
        public bool IfStatic { get; set; }   //是否为固定元素不可删除那种      

        public ProCaptureObj()
        {
            
        }

        public object Clone()
        {
            return this.MemberwiseClone();
        }

        /// <summary>
        /// 深度克隆
        /// </summary>
        /// <returns></returns>
        public object DeepClone()
        {
            //新建一个
            ProCaptureObj newattr = new ProCaptureObj();

            //复制属性
            PropertyInfo[] fromFields = typeof(ProCaptureObj).GetProperties();
            PubFunction.SetProperties(fromFields, this, newattr);

            newattr.CopyParent(this as ProCaptureObj);
            return newattr;

        }

        public void CopyParent(ProCaptureObj parent)
        {
            //复制属性
            PropertyInfo[] fromFields = typeof(ProCaptureObj).GetProperties();
            PubFunction.SetProperties(fromFields, parent, this);           

        }


        //private static List<ProCaptureObj> TableToList(DataTable dt)
        //{
        //    if (dt == null) return null;
        //    List<ProCaptureObj> list = new List<ProCaptureObj>();
        //    ProCaptureObj m = null;
        //    foreach (DataRow dr in dt.Rows)
        //    {
        //        m = new ProCaptureObj();

        //        m.RelateAttrID = dr["RelateAttrID"].ToString();
        //        //m.PID = dr["PID"].ToString();
        //        m.ObAttrID = dr["ObAttrID"].ToString();
        //        m.Seq = int.Parse(dr["seq"].ToString());                
        //        m.IfStatic = dr["IfStatic"].ToString() == "1";
        //        m.DataIndex =int.Parse(dr["DataIndex"].ToString());              

                
        //        list.Add(m);
        //    }
        //    return list;
        //}

        //获取数据库中所有元素
        private static void GetAllEleItem()
        {
            //PtlConsts.easyDb.Clear();
            //PtlConsts.easyDb.TableName = ptltable;
            ////PtlConsts.easyDb.TableName = "T_CaptureObjs a,V_ObattrMth b";
            ////PtlConsts.easyDb.SetRelateFieldParameter(true, "a.ID", "=", "b.id");            
            //PtlConsts.easyDb.SetOrder("ObAttrID,seq");
            //dtAll = PtlConsts.easyDb.Select();
            //if (dtAll == null) return;
            //dtAll.TableName = ptltable;
            //EleItemlst = TableToList(dtAll);

            var list = protocolDbRepository.GetAllCaptureObjs().Result;

            foreach (var item in list)
            {
                var m = new ProCaptureObj();

                m.RelateAttrID = item.RelateAttrID;
                m.ObAttrID = item.ObAttrID;
                m.Seq = item.seq;
                m.IfStatic = item.IfStatic == 1;
                m.DataIndex = item.DataIndex;

                EleItemlst.Add(m);
            }
        }


        /// <summary>
        /// 获取所有数据的集合
        /// </summary>
        /// <returns></returns>
        public static DataTable GetEleSchItemDateTable()
        {
            if (dtAll == null)
                GetAllEleItem();
            return dtAll;
        }


        ////获取已经整理了上下级关系的元素列表  shaunwang 2016-9-28
        //public static void GetTreeEleLst()
        //{
        //    EleTreelist.Clear();
        //    GetAllEleItem();
        //    foreach (ProCaptureObj pesi in EleItemlst)
        //    {
        //        if (pesi.PID == "")
        //        {
        //            pesi.EleLst.Clear();  //shaunwang 2016-9-23  获取子节点前先清空一下，防止重复加载                    
        //            if (pesi.IfParent)
        //                GetChildEleItem(pesi);  //获取子节点
        //            pesi.GetEleInSch();
        //            EleTreelist.Add(pesi);
        //        }
        //    }

        //}


        ////刷新元素列表
        //private static void RfreshTreeEleLst()
        //{
        //    EleTreelist.Clear();
        //    foreach (ProCaptureObj pesi in EleItemlst)
        //    {
        //        if (pesi.PID == "")
        //        {
        //            pesi.EleLst.Clear();  //shaunwang 2016-9-23  获取子节点前先清空一下，防止重复加载                    
        //            if (pesi.IfParent)
        //                GetChildEleItem(pesi);  //获取子节点
        //            pesi.GetEleInSch();
        //            EleTreelist.Add(pesi);
        //        }
        //    }

        //}

        /// <summary>
        /// 删除某属性下的所有元素
        /// </summary>
        /// <param name="schid"></param>
        public static void RemoveEleItem(string ObAttrID)
        {
            for (int i = EleItemlst.Count - 1; i >= 0; i--)
            {
                if (EleItemlst[i].ObAttrID == ObAttrID && !EleItemlst[i].IfStatic)
                    EleItemlst.RemoveAt(i);
            }

           // RfreshTreeEleLst();
        }

        /// <summary>
        /// 添加新的元素
        /// </summary>
        /// <param name="newitem"></param>
        /// <param name="checkID">如果已有ID是否就不添加了</param>
        public static int AddEleItem(ProCaptureObj newitem, bool checkID)
        {
            if (checkID)
            {
                bool haveit = false;
                for (int i = 0; i < EleItemlst.Count; i++)
                {
                    if (EleItemlst[i].ObAttrID == newitem.ObAttrID &&
                        EleItemlst[i].RelateAttrID == newitem.RelateAttrID &&
                        EleItemlst[i].DataIndex==newitem.DataIndex)
                    {
                        haveit = true;
                        return 0;
                    }
                }

            }
            EleItemlst.Add(newitem);          
            return 1;
        }

        /// <summary>
        /// 根据属性ID搜索所有元素
        /// </summary>
        /// <param name="sID"></param>
        /// <returns></returns>
        public static List<ProCaptureObj> GetEleItemBySchID(string sID)
        {
            List<ProCaptureObj> list = new List<ProCaptureObj>();
            if (string.IsNullOrEmpty(sID))
                return list;
            if (EleItemlst.Count == 0)
                GetAllEleItem();

            foreach (ProCaptureObj pesi in EleItemlst)
            {
                if (pesi.ObAttrID == sID)
                    list.Add(pesi);
            }
            return list;
        }     


        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="insertFlag">true时是插入增加,false更新</param>
        /// <returns></returns>
        public int SaveEleItem(bool insertFlag)
        {
            //PtlConsts.easyDb.Clear();
            //PtlConsts.easyDb.TableName = ptltable;
           
            //PtlConsts.easyDb.SetFieldValue("seq", Seq.ToString(), EasyDataType.String);
            
            //PtlConsts.easyDb.SetFieldValue("IfStatic", IfStatic ? "1" : "0", EasyDataType.Number);

            CaptureObjs captureObjs = new CaptureObjs();
            captureObjs.seq = Seq;
            captureObjs.IfStatic = IfStatic ? 1 : 0;

            if (insertFlag)
            {
                //PtlConsts.easyDb.SetFieldValue("RelateAttrID", RelateAttrID, EasyDataType.String);
                //PtlConsts.easyDb.SetFieldValue("ObAttrID", ObAttrID, EasyDataType.String);
                //PtlConsts.easyDb.SetFieldValue("DataIndex", DataIndex.ToString(), EasyDataType.String);
                //int rs = PtlConsts.easyDb.Insert();

                captureObjs.RelateAttrID = RelateAttrID;
                captureObjs.ObAttrID = ObAttrID;
                captureObjs.DataIndex = DataIndex;
                int rs = protocolDbRepository.Insert(captureObjs);

                if (rs > 0)
                    rs = AddEleItem(this, true);
                return rs;
            }
            else
            {
                //PtlConsts.easyDb.SetWhereParameter(true, "RelateAttrID", "=", RelateAttrID, EasyDataType.String);
                //PtlConsts.easyDb.SetWhereParameter(true, "ObAttrID", "=", ObAttrID, EasyDataType.String);
                //PtlConsts.easyDb.SetWhereParameter(true,"DataIndex", "=",DataIndex.ToString(), EasyDataType.String);
                //return PtlConsts.easyDb.Update();

                captureObjs.RelateAttrID = RelateAttrID;
                captureObjs.ObAttrID = ObAttrID;
                captureObjs.DataIndex = DataIndex;
                return protocolDbRepository.Update(captureObjs);
            }
        }        

        /// <summary>
        /// 获取新的SEQ
        /// </summary>
        /// <param name="sID"></param>
        /// <returns></returns>
        private static string GetNewSEQ(string sID)
        {
            if (string.IsNullOrEmpty(sID)) return "1";

            //PtlConsts.easyDb.Clear();
            //PtlConsts.easyDb.TableName = ptltable;
            //PtlConsts.easyDb.SetSelectColumns("max(seq)+1");
            //PtlConsts.easyDb.SetWhereParameter(true, "ObAttrID", "=", sID, EasyDataType.String);
            //DataTable dt = PtlConsts.easyDb.Select();
            //if (dt.Rows.Count > 0)
            //    return dt.Rows[0][0].ToString();
            //else
            //    return "1";

            return protocolDbRepository.GetNewSEQ(sID).ToString();
        }

        /// <summary>
        /// 删除某个方案的所有元素 
        /// </summary>
        /// <param name="ifall">true时删除所有,false时不删除固定项</param>
        /// <returns></returns>
        public static int DeleteItemByAttrID(string sID, bool ifall)
        {
            if (string.IsNullOrEmpty(sID)) return 1;
            try
            {
                //PtlConsts.easyDb.Clear();
                //PtlConsts.easyDb.TableName = ptltable;
                //PtlConsts.easyDb.SetWhereParameter(true, "ObAttrID", "=", sID, EasyDataType.String);
                //if (!ifall)
                //{
                //    PtlConsts.easyDb.SetWhereParameter(true, "(IfStatic", "<>", "1", EasyDataType.Number);
                //    PtlConsts.easyDb.SetWhereParameter(false, "IfStatic)", "is", "null", EasyDataType.Number);
                //}
                //int rs = PtlConsts.easyDb.Delete();

                int rs = protocolDbRepository.Delete(sID, ifall);
                if (rs > 0)
                    RemoveEleItem(sID);
                return rs;
            }
            catch
            {
                return -1;
            }
        }      


        /// <summary>
        /// 根据ID判别元素是否已存在
        /// </summary>
        /// <returns></returns>
        private bool IsExistSchByID()
        {
            try
            {
                //PtlConsts.easyDb.Clear();
                //PtlConsts.easyDb.TableName = ptltable;
                //PtlConsts.easyDb.SetWhereParameter(true, "ObAttrID", "=", ObAttrID, EasyDataType.Number);
                //PtlConsts.easyDb.SetWhereParameter(true, "RelateAttrID", "=", RelateAttrID, EasyDataType.Number);
                //PtlConsts.easyDb.SetWhereParameter(true, "DataIndex", "=", DataIndex.ToString(), EasyDataType.Number);
                //return PtlConsts.easyDb.Select().Rows.Count > 0 ? true : false;

                var obj = protocolDbRepository.Find(ObAttrID, RelateAttrID, DataIndex);
                if (obj != null)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 根据记录集导入数据库（元素方案文件导入时使用）by xd
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        //public static bool DataTbleImportDB(DataTable dt)
        //{
        //    try
        //    {
        //        List<ProCaptureObj> EleItemlst = ProCaptureObj.TableToList(dt);
        //        foreach (ProCaptureObj proitem in EleItemlst)
        //        {
        //            if (proitem.SaveEleItem(!proitem.IsExistSchByID()) <= 0)
        //            {
        //                return false;
        //            }
        //        }
        //        return true;
        //    }
        //    catch
        //    {
        //        return false;
        //    }
        //}

        public static int GetEleCountBySch(string Sid)
        {
            //PtlConsts.easyDb.Clear();
            //PtlConsts.easyDb.TableName = ptltable;
            //PtlConsts.easyDb.SetWhereParameter(true, "ObAttrID", "=", Sid, EasyDataType.String);            
            //DataTable dt = PtlConsts.easyDb.Select();
            //return dt.Rows.Count;

            var list = protocolDbRepository.GetByObAttrID(Sid);
            return list.Count();
        }
    }
}

